<template>
  <a-modal
    title="新增业务"
    :width="650"
    :visible="visible"
    @cancel="handleCancel"
    @ok="handleSubmit"
    :confirmLoading="confirmLoading"
    :destroyOnClose="true"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-form-item v-bind="formItemLayout" label="业务名称" hasFeedback>
          <a-input
            v-decorator="['name', { rules: [{ required: true, message: '名称不能为空' }] }]"
            :maxLength="20"
            placeholder="输入业务名称"
          />
        </a-form-item>
        <a-form-item v-bind="formItemLayout" label="业务缩写" hasFeedback>
          <a-input
            v-decorator="[
              'code',
              {
                rules: [
                  { required: true, message: '业务缩写不能为空' },
                  { pattern: new RegExp(/^[a-zA-Z]*$/), message: '只能输入大小写' },
                ],
              },
            ]"
            :maxLength="20"
            placeholder="输入业务业务缩写"
          />
        </a-form-item>
        <a-form-item v-bind="formItemLayout" label="标签" hasFeedback>
          <a-select
            mode="multiple"
            v-decorator="['tags', { rules: [{ required: true, message: '标签不能为空' }] }]"
            placeholder="选择标签"
          >
            <a-select-option :key="item.name" v-for="item in tags">
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item v-bind="formItemLayout" label="描述" hasFeedback>
          <a-textarea v-decorator="['description', {}]" :rows="4" placeholder="输入描述" />
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import { sqlSelect, sqlFindOne, sqlInsert } from '@/api/sql'
import { mapGetters } from 'vuex'
export default {
  name: 'CategoryCreateModal',
  data () {
    return {
      confirmLoading: false,
      visible: false,
      formItemLayout: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 4 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 18 }
        }
      },
      form: this.$form.createForm(this),
      tags: []
    }
  },
  created () {},
  computed: {
    userInfo () {
      return this.$store.getters.userInfo
    }
  },
  methods: {
    ...mapGetters(['nickname']),

    /**
     * 初始化
     */
    async init () {
      // 显示弹框
      this.visible = true
      this.tags = await this.getTags()
    },

    /**
     * 关闭
     */
    handleCancel () {
      this.visible = false
    },

    /**
     * 提交
     */
    handleSubmit () {
      const {
        form: { validateFields }
      } = this
      this.confirmLoading = true
      validateFields((errors, values) => {
        console.log('errors:', errors, 'val:', values)
        if (!errors) {
          // 检测数据是否存在
          this.verify(values.code).then((res) => {
            console.log(res)
            if (res.id) {
              this.$notification['error']({
                message: '提示',
                description: `已经存在相同的业务索引${res.code}`
              })
              this.confirmLoading = false
            } else {
              this.create(values).then((response) => {
                console.log('response', response)
                this.visible = false
                this.confirmLoading = false
                this.$notification['success']({
                  message: '提示',
                  description: '数据新建成功！'
                })
                // 延迟发送事件，解决列表刷新还是老数据的问题
                setTimeout(() => {
                  console.log('setTimeout')
                  this.$emit('ok', values)
                }, 2000)
              })
            }
          })
        } else {
          this.confirmLoading = false
        }
      })
    },

    /**
     * 新建数据
     */
    create (values) {
      console.log(values)
      values.tags = values.tags || ''
      values.description = values.description || ''
      var params = {
        sql: `insert into t_category (name,create_by,modify_by,code,description,tags) values ('${values.name}','${this.userInfo.login}','${this.userInfo.login}','${values.code}','${values.description}','${values.tags}')`
      }
      return new Promise((resolve, reject) => {
        sqlInsert(params).then(
          (res) => {
            resolve(res)
          },
          (error) => {
            reject(error)
          }
        )
      })
    },

    /**
     * 检测是否重复
     */
    verify (code) {
      const params = {
        sql: `select * from t_category where code='${code}'`
      }
      return new Promise((resolve, reject) => {
        sqlFindOne(params).then(
          (res) => {
            resolve(res)
          },
          (error) => {
            console.log(error)
            resolve(error)
          }
        )
      })
    },

    /**
     * 获取标签
     */
    getTags () {
      const params = {
        sql: `select * from t_category_tag`
      }
      return new Promise((resolve, reject) => {
        sqlSelect(params).then(
          (res) => {
            resolve(res)
          },
          (error) => {
            console.log(error)
            resolve(error)
          }
        )
      })
    }
  }
}
</script>

<style lang="less" scoped>
</style>
